import { ipcMain, dialog } from 'electron'

const path = require('path')
const fs = require('fs')
function getMimeType(filePath) {
  const ext = filePath.split('.').pop().toLowerCase()
  const mimeTypes = {
    mp3: 'audio/mpeg',
    wav: 'audio/wav',
    ogg: 'audio/ogg',
    m4a: 'audio/mp4',
    aac: 'audio/aac'
  }
  return mimeTypes[ext] || 'audio/mpeg'
}
//获取文件信息
const openFile = () => {
  ipcMain.handle('open-file', async (_, arg: string = 'all') => {
    let file = {
      all: ['*'],
      img: ['jpg', 'jpeg', 'png', 'gif', 'bmp'],
      audio: ['mp3', 'wav', 'ogg', 'm4a'],
      video: ['mp4', 'avi', 'mov', 'wmv']
    }
    const result = await dialog.showOpenDialog({
      properties: ['openFile', 'multiSelections'],
      filters: [
        { name: '文件', extensions: file[arg] || file.all },
        { name: '所有文件', extensions: ['*'] }
      ]
    })
    if (result.canceled) return []
    console.log('result.filePaths', result.filePaths)
    function getaudioUrl(filePath: string) {
      const fileBuffer = fs.readFileSync(filePath)
      const stats = fs.statSync(filePath)
      const fileSize = stats.size
      const arrayBuffer = fileBuffer.buffer.slice(
        fileBuffer.byteOffset,
        fileBuffer.byteOffset + fileBuffer.byteLength
      )

      // 或者转换为 Base64（前端也可直接播放）
      const base64Data = fileBuffer.toString('base64')
      const mimeType = getMimeType(filePath)
      return {
        arrayBuffer: arrayBuffer,
        base64Data: base64Data,
        mimeType: mimeType,
        fileName: filePath.split(/[\\/]/).pop(),
        name: path.basename(filePath),
        size: fileSize
      }
    }
    return getaudioUrl(result.filePaths[0])

    // 读取文件信息
    // return result.filePaths.map((filePath) => {
    //   const stats = fs.statSync(filePath)
    //   return {
    //     path: filePath,
    //     name: path.basename(filePath),
    //     size: stats.size,
    //     type: path.extname(filePath).substring(1),
    //     data: getaudioUrl(filePath)
    //   }
    // })
  })
}
  //获取打开的文件夹路径
const openFolderPath = () => {

  ipcMain.handle('open-folder', async () => {
    const result = await dialog.showOpenDialog({
      properties: ['openDirectory']
    })
    if (result.canceled) return []
    return result.filePaths[0]
  })
}
//提示选择文件夹路径
const showOpenFolderDialog = () => {
  ipcMain.handle('show-open-folder-dialog', async (_, arg: string = '选择文件夹', title: string = '选择文件夹') => {
    const result = await dialog.showOpenDialog({
      properties: ['openDirectory'],
      message: arg,
      title: title
    })
    if (result.canceled) return []
    return result.filePaths[0]
  })
}



export default {
  openFile,
  openFolderPath,
  showOpenFolderDialog

}
